//
//  CountDownButton.m
//  Elife
//
//  Created by 拓客营 on 2022/4/15.
//

#import "CountDownButton.h"

@implementation CountDownButton

+(instancetype)buttonWithType:(UIButtonType)buttonType{
    CountDownButton *btn = [super buttonWithType:buttonType];
    if (btn) {
        
    }
    return btn;
}

#pragma -mark touche action
-(void)addToucheHandler:(CountDownButton *)btn hander:(TouchedDownBlock)touchHandler;{
    _touchedDownBlock = [touchHandler copy];
    if (_touchedDownBlock) {
        _touchedDownBlock(btn,btn.tag);
    }
}

-(void)touched:(CountDownButton*)sender{
    NSLog(@"时间响应");
   
}

#pragma -mark count down method
-(void)startWithSecond:(int)totalSecond
{
    _totalSecond = totalSecond;
    _second = totalSecond;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerStart:) userInfo:nil repeats:YES];
    _startDate = [NSDate date];
    [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
}
-(void)timerStart:(NSTimer *)theTimer {
    double deltaTime = [[NSDate date] timeIntervalSinceDate:_startDate];
    
    _second = _totalSecond - (int)(deltaTime+0.5) ;
    if (_second< 0.0){
        [self stop];
    }else{
        if (_didChangeBlock){
            [self setTitle:_didChangeBlock(self,_second) forState:UIControlStateNormal];
        }else{
            NSString *title = [NSString stringWithFormat:@"%02d秒",_second];
            [self setTitle:title forState:UIControlStateNormal];
        }
    }
}

- (void)stop{
    if (_timer) {
        if ([_timer respondsToSelector:@selector(isValid)]){
            if ([_timer isValid]){
                [_timer invalidate];
                _second = _totalSecond;
                if (_didFinishedBlock){
                    [self setTitle:_didFinishedBlock(self,_totalSecond)forState:UIControlStateNormal];
                }else{
                    [self setTitle:@"重新获取" forState:UIControlStateNormal];
                }
            }
        }
    }
}
#pragma -mark block
-(void)didChange:(DidchangeBlock)didChangeBlock{
    _didChangeBlock = [didChangeBlock copy];
}
-(void)didFinished:(DidFinishedBlock)didFinishedBlock{
    _didFinishedBlock = [didFinishedBlock copy];
}

@end
